package com.wonderful.serialportdemo

import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.ubtrobot.serialportlib.serial.SerialDataListener
import com.ubtrobot.serialportlib.serial.SerialManager

class MainActivity : AppCompatActivity() {

    var tvContent: TextView? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        tvContent = findViewById(R.id.tv_content)

        findViewById<Button>(R.id.btn_open_port).setOnClickListener {
            initSerialPort()
        }

        findViewById<Button>(R.id.btn_close_port).setOnClickListener {
            SerialManager.getInstance().closeSerialPort()
            SerialManager.getInstance().unRegisterListener(mListener)
        }

    }

    private val mListener: SerialDataListener =
        SerialDataListener { data ->
            Log.i("MainActivity", "获取到数据... $data")
            runOnUiThread { tvContent?.text = data }
        }

    private fun initSerialPort() {
        SerialManager.getInstance().openSerialPort(
            "/dev/ttyS1", 115200
        ) { success, errorMsg ->
            if (success) {
                Log.i("MainActivity", "success:")
                SerialManager.getInstance().registerListener(mListener)
            } else {
                Log.i("MainActivity", "failed: $errorMsg")
            }
        }
    }

}